<?php
/**
 * User: xuhong
 * Date: 2018/10/30
 */

namespace extend\wechat\mp;


class QrCode
{
    /**
     * 生成二维码
     * @param $senstr
     * @param string $type
     * @return string
     */
    public static function createQrCode($senstr, $type = "limit")
    {
        if ($type == "limit") {
            $res = self::createLimit($senstr, 2592000);
        } else {
            $res = self::createPermanent($senstr);
        }
        $res = json_decode($res, true);
        if (!empty($res["ticket"])) {
            return self::showQrCode($res["ticket"]);
        } else {
            exit("生成二维码失败，请检查程序");
        }
    }


    /**
     * 创建临时二维码
     * @param $sence_str
     * @param int $expire_seconds
     * @return bool|string
     */
    protected static function createLimit($sence_str, $expire_seconds = 604800)
    {
        $access_token = Voucher::accessToken()['access_token'];

        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$access_token}";
        $data = [
            'expire_seconds' => $expire_seconds,
            'action_name' => 'QR_STR_SCENE',//默认采用字符串而非ID模式
            'action_info' => [
                'scene' => [
                    'scene_str' => $sence_str,
                ]
            ],
        ];
        $data = json_encode($data, JSON_UNESCAPED_UNICODE);

        return postRequest($url, $data);
    }

    /**
     * 创建永久二维码
     * @param $sence_str
     * @return bool|string
     */
    protected static function createPermanent($sence_str)
    {
        $access_token = Voucher::accessToken()['access_token'];

        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$access_token}";
        $data = [
            'action_name' => 'QR_LIMIT_STR_SCENE',//默认采用字符串而非ID模式
            'action_info' => [
                'scene' => [
                    'scene_str' => $sence_str,
                ]
            ],
        ];
        $data = json_encode($data, JSON_UNESCAPED_UNICODE);

        return postRequest($url, $data);
    }

    public static function showQrCode($ticket)
    {
        return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={$ticket}";
    }
}